import { useEffect, useState, useMemo } from 'react';
import { Upload, Download, Palette, Sliders, Volume2 } from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/store';
import { setBreadcrumbs } from '@/store/slices/uiSlice';
import { selectClip, addEffect, addTransition } from '@/store/slices/timelineSlice';
import TimelineEditor from '@/components/video/TimelineEditor';
import EffectsPanel from '@/components/video/EffectsPanel';
import TransitionsPanel from '@/components/video/TransitionsPanel';
import PreviewPlayer from '@/components/video/PreviewPlayer';
import ExportPanel from '@/components/video/ExportPanel';

const VideoEditor: React.FC = () => {
  const dispatch = useAppDispatch();
  const { clips, duration, selectedClipId } = useAppSelector(state => state.timeline);

  const [activeTab, setActiveTab] = useState<'properties' | 'export'>('properties');

  // 获取当前选中的剪辑
  const selectedClip = useMemo(() => {
    return clips.find(clip => clip.id === selectedClipId);
  }, [clips, selectedClipId]);

  // 处理剪辑选择
  const handleClipSelect = (clipId: string | null) => {
    dispatch(selectClip(clipId));
  };

  // 处理特效添加
  const handleAddEffect = (effectType: string) => {
    if (selectedClipId) {
      const effect = {
        id: `effect-${Date.now()}`,
        type: effectType as any,
        name: effectType === 'color_correction' ? '色彩校正' : 
               effectType === 'blur' ? '模糊效果' : 
               effectType === 'sharpen' ? '锐化' : '降噪',
        parameters: {},
        startTime: 0,
        duration: selectedClip?.duration || 0,
        enabled: true,
      };
      dispatch(addEffect({ clipId: selectedClipId, effect }));
    }
  };

  // 处理转场添加
  const handleAddTransition = (transitionType: string) => {
    if (selectedClipId) {
      const transition = {
        id: `transition-${Date.now()}`,
        type: transitionType as any,
        name: transitionType === 'fade' ? '淡入淡出' : 
               transitionType === 'slide' ? '滑动效果' : '溶解效果',
        duration: 1,
        position: 'start' as const,
        parameters: {},
      };
      dispatch(addTransition({ clipId: selectedClipId, transition }));
    }
  };

  // 格式化时间
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  useEffect(() => {
    dispatch(setBreadcrumbs([{ label: '仪表板', path: '/dashboard' }, { label: '视频编辑器' }]));
  }, [dispatch]);

  const handleImportVideo = () => {
    // 处理视频导入逻辑
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'video/*';
    input.onchange = e => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        // 这里应该调用导入视频的逻辑
        console.log('导入视频:', file.name);
      }
    };
    input.click();
  };

  return (
    <div className='video-editor'>
      {/* Header */}
      <div className='editor-header'>
        <div className='header-content'>
          <div className='header-info'>
            <h1>视频编辑器</h1>
            <p>
              {clips.length > 0
                ? `${clips.length} 个剪辑片段 | 总时长: ${Math.floor(duration)} 秒`
                : '拖放视频文件开始编辑'}
            </p>
          </div>
          <div className='header-actions'>
            <button className='import-btn' onClick={handleImportVideo}>
              <Upload />
              <span>导入视频</span>
            </button>
            <button className='export-btn'>
              <Download />
              <span>导出项目</span>
            </button>
          </div>
        </div>
      </div>

      {/* Main Editor Area */}
      <div className='editor-content'>
        {/* Left Panel - Tools and Effects */}
        <div className='left-panel'>
          <div className='panel-section'>
            <h3>特效和滤镜</h3>
            <div className='effects-grid'>
              <button className='effect-btn'>
                <div className='effect-icon' style={{ background: @primary-color }} />
                <span className='effect-name'>色彩校正</span>
              </button>
              <button className='effect-btn'>
                <div className='effect-icon' style={{ background: @purple-500 }} />
                <span className='effect-name'>模糊效果</span>
              </button>
              <button className='effect-btn'>
                <div className='effect-icon' style={{ background: @green-500 }} />
                <span className='effect-name'>锐化</span>
              </button>
              <button className='effect-btn'>
                <div className='effect-icon' style={{ background: @red-500 }} />
                <span className='effect-name'>降噪</span>
              </button>
            </div>
          </div>

          <div className='panel-section'>
            <h3>转场效果</h3>
            <div className='transitions-list'>
              <button className='transition-btn'>
                <span>淡入淡出</span>
              </button>
              <button className='transition-btn'>
                <span>滑动效果</span>
              </button>
              <button className='transition-btn'>
                <span>溶解效果</span>
              </button>
            </div>
          </div>

          <div className='panel-section'>
            <h3>音频工具</h3>
            <div className='audio-tools'>
              <button className='audio-btn'>
                <span>音频轨道</span>
              </button>
              <button className='audio-btn'>
                <span>音量调节</span>
              </button>
              <button className='audio-btn'>
                <span>音频特效</span>
              </button>
            </div>
          </div>
        </div>

        {/* Center Panel - Preview and Timeline */}
        <div className='center-panel'>
          <div className='preview-container'>
            <PreviewPlayer />
          </div>
          <div className='timeline-container'>
            <TimelineEditor />
          </div>
        </div>

        {/* Right Panel - Properties and Settings */}
        <div className='right-panel'>
          <div className='tab-nav'>
            <button
              className={`tab-btn ${activeTab === 'properties' ? 'active' : ''}`}
              onClick={() => setActiveTab('properties')}
            >
              剪辑属性
            </button>
            <button
              className={`tab-btn ${activeTab === 'effects' ? 'active' : ''}`}
              onClick={() => setActiveTab('effects')}
            >
              特效
            </button>
            <button
              className={`tab-btn ${activeTab === 'transitions' ? 'active' : ''}`}
              onClick={() => setActiveTab('transitions')}
            >
              转场
            </button>
            <button
              className={`tab-btn ${activeTab === 'export' ? 'active' : ''}`}
              onClick={() => setActiveTab('export')}
            >
              导出
            </button>
          </div>

          <div className='tab-content'>
            {activeTab === 'properties' && (
              <>
                <div className='property-group'>
                  <h3>剪辑属性</h3>
                  <div className='property-item'>
                    <label>开始时间</label>
                    <input
                      type='text'
                      placeholder='00:00:00'
                      value={formatTime(selectedClip?.trackStartTime || 0)}
                      readOnly
                    />
                  </div>
                  <div className='property-item'>
                    <label>持续时间</label>
                    <input
                      type='text'
                      placeholder='00:00:00'
                      value={formatTime(selectedClip?.duration || 0)}
                      readOnly
                    />
                  </div>
                  <div className='property-item'>
                    <label>播放速度</label>
                    <select
                      value={1}
                      onChange={e => {
                        console.log('设置播放速度:', e.target.value);
                      }}
                    >
                      <option value='0.25'>0.25x</option>
                      <option value='0.5'>0.5x</option>
                      <option value='1'>1x</option>
                      <option value='1.5'>1.5x</option>
                      <option value='2'>2x</option>
                    </select>
                  </div>
                </div>

                <div className='property-group'>
                  <h3>视频属性</h3>
                  <div className='property-item'>
                    <label>分辨率</label>
                    <select>
                      <option value='1080p'>1920x1080 (1080p)</option>
                      <option value='720p'>1280x720 (720p)</option>
                      <option value='480p'>854x480 (480p)</option>
                    </select>
                  </div>
                  <div className='property-item'>
                    <label>帧率</label>
                    <select>
                      <option value='30'>30 fps</option>
                      <option value='25'>25 fps</option>
                      <option value='24'>24 fps</option>
                      <option value='60'>60 fps</option>
                    </select>
                  </div>
                </div>
              </>
            )}

            {activeTab === 'effects' && selectedClip && (
              <EffectsPanel
                effects={selectedClip.effects || []}
                onAddEffect={handleAddEffect}
                onRemoveEffect={(effectId) => {
                  // 需要实现移除特效的逻辑
                  console.log('移除特效:', effectId);
                }}
                onUpdateEffect={(effectId, updates) => {
                  // 需要实现更新特效的逻辑
                  console.log('更新特效:', effectId, updates);
                }}
              />
            )}

            {activeTab === 'transitions' && selectedClip && (
              <TransitionsPanel
                transitions={selectedClip.transitions || []}
                onAddTransition={handleAddTransition}
                onRemoveTransition={(transitionId) => {
                  // 需要实现移除转场的逻辑
                  console.log('移除转场:', transitionId);
                }}
                onUpdateTransition={(transitionId, updates) => {
                  // 需要实现更新转场的逻辑
                  console.log('更新转场:', transitionId, updates);
                }}
              />
            )}

            {activeTab === 'export' && <ExportPanel />}
          </div>
        </div>
      </div>
    </div>
  );
};

import './styles.less';
import '@/components/video/preview-export.less';

export default VideoEditor;
